package socket;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class ClientGUI extends JFrame {

    private Socket socket;
    private JTextArea chatArea;
    private JTextField inputField;
    private JButton sendButton;
    private PrintWriter output;
    private BufferedReader input;
    private String nickname;

    public ClientGUI() {
        super("Chat Client");

        // 设置窗口大小
        setSize(400, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 创建聊天记录区域
        chatArea = new JTextArea();
        chatArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(chatArea);

        // 创建输入框
        inputField = new JTextField(20); // 设置初始宽度为20个字符宽
        inputField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage(inputField.getText());
                inputField.setText("");
            }
        });

        // 创建发送按钮
        sendButton = new JButton("Send");
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage(inputField.getText());
                inputField.setText("");
            }
        });

        // 布局管理器
        setLayout(new BorderLayout());

        // 添加组件
        add(scrollPane, BorderLayout.CENTER);
        JPanel bottomPanel = new JPanel();
        bottomPanel.add(inputField);
        bottomPanel.add(sendButton);
        add(bottomPanel, BorderLayout.SOUTH);

        // 连接到服务器
        try {
            System.out.println("正在连接服务端");
            socket = new Socket("172.88.28.23", 8088);
            System.out.println("连接成功");

            // 获取输出流
            output = new PrintWriter(socket.getOutputStream(), true);

            // 输入用户昵称
            nickname = JOptionPane.showInputDialog(this, "请输入昵称：");
            while (nickname == null || nickname.trim().isEmpty()) {
                nickname = JOptionPane.showInputDialog(this, "昵称不合法，请重新输入");
            }
            output.println(nickname);
            System.out.println("欢迎你" + nickname + "请开始聊天吧");

            // 启动读取线程
            Thread readThread = new Thread(new ServerHandler());
            readThread.setDaemon(true);
            readThread.start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void sendMessage(String message) {
        if (message.trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "输入不能为空");
            return;
        }
        output.println(message);
    }

    private class ServerHandler implements Runnable {
        public void run() {
            try {
                input = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
                String message;
                while ((message = input.readLine()) != null) {
                    chatArea.append(message + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            ClientGUI clientGUI = new ClientGUI();
            clientGUI.setVisible(true);
        });
    }
}
